"""
登录接口
"""
# sfb
from fastapi import APIRouter
from pydantic import BaseModel

# zjb
from core.utils import create_access_token, computeMD5, SelfJSONResponse
from models import User, Menus, RoleGroup_Menus
from schemas import User_Pydantic, Menus_Pydantic

login = APIRouter(tags=["认证相关"], prefix="/userAction")


class loginUser(BaseModel):
    loginname: str
    pwd: str

async def getMenuTree(groupid):
    rm = await RoleGroup_Menus.filter(groupid=groupid).all()
    menusAll = list()
    for m in rm:
        menu = await Menus.filter(menuid=m.menuid).first()
        menusAll.append(menu)
    resultValue = list()
    for menu in menusAll:
        if menu.parentMenuid == None or str(menu.parentMenuid).strip() == "":
            level_1 = dict()
            level_1["menuid"] = menu.menuid
            level_1["title"] = menu.title
            level_1["icon"] = menu.icon
            # 二级列表
            level2List = list()
            for submenu in menusAll:
                if submenu.menuid != None and submenu.parentMenuid == menu.menuid:
                    level_2 = dict()
                    level_2["routerURL"] = submenu.routerURL
                    level_2["menuid"] = submenu.menuid
                    level_2["title"] = submenu.title
                    level2List.append(level_2)
            # 追加子路由
            level_1["children"] = level2List
            # 往结果list中追加进当前对象
            resultValue.append(level_1)
    return resultValue


@login.post("/loginVerify", description="登录验证")
async def login_verify(user: loginUser):

    # 查询用户
    try:
        userQuery = await User.get(loginname=user.loginname, pwd=computeMD5(user.pwd))
    except:
        return SelfJSONResponse(code=500, msg="用户名或密码错误！")

    userInfo = (await User_Pydantic.from_tortoise_orm(userQuery)).dict()
    userInfo['pwd'] = user.pwd

    return SelfJSONResponse(code=200,
                            data={'token': create_access_token(user),
                                  'routes': await getMenuTree(userInfo['groupid']),
                                  'userInfo': userInfo},
                            msg="操作成功")
